import axios from 'axios';
import mintUi from './mintUi';
import constant from './constant';
import {createStore} from '@/.lavas/store';
let store = createStore();

axios.defaults.timeout = 10000;            // 响应时间
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';      // 配置请求头
axios.defaults.baseURL = constant.ajaxUrl();  // 配置接口地址
// POST传参序列化(添加请求拦截器)
axios.interceptors.request.use((config) => {
  const userToken = sessionStorage.getItem('userToken');
  if (userToken) {
    config.headers.common = {
      'Tcsl-Loongboss-Token': userToken
    };
  }
  return config;
}, (error) => {
  mintUi.openToast('传参错误');
  return Promise.reject(error);
});
// 返回状态判断(添加响应拦截器)
axios.interceptors.response.use((res) => {
  // 对响应数据做些事
  if (res.data.code === '-10006') {
    mintUi.openAlert(res.data.msg).then(result => {
      let te = window.location.href.split('/');
      const url = te[0] + te[1] +'//'+ te[2] + '/login';
      window.location.href = url;
    });
  } else if (res.data.code !== '0') {
    mintUi.openToast(res.data.msg);
    return Promise.reject(res.data);
  }
  return res;
}, (error) => {
  mintUi.openToast('网络异常');
  return Promise.reject(error);
});
// 返回一个Promise(发送post请求)
export default {
  axiosCommon (url, params, type) {
    return new Promise((resolve, reject) => {
      axios({
        method: type,
        url: url,
        data: params
      }).then(response => {
        store.dispatch('login/setToken', response.headers['tcsl-loongboss-token']);
        resolve(response.data.data);
      }, err => {
        reject(err);
      }).catch((error) => {
        mintUi.openToast('出现异常');
        reject(error);
      });
    });
  },

  postService (url, params) {
    return this.axiosCommon(url, params, 'post');
  },
  postWithSCode (url, params) {
    params.storeCode = store.state.shopAlter.store.storeCode ? [store.state.shopAlter.store.storeCode] : [];
    params.groupCode = store.state.shopAlter.store.groupCode;
    params.businessModelName = store.state.shopAlter.mode.modeName || '';
    params.cityCode = store.state.shopAlter.mode.cityCode || '';
    return this.axiosCommon(url, params, 'post');
  },
  getService (url) {
    return this.axiosCommon(url, '', 'get');
  },
  delService (url, params) {
    return this.axiosCommon(url, params, 'delete');
  },
  putService (url, params) {
    return this.axiosCommon(url, params, 'put');
  }
};
